package org.epidroid.epidroid.androsoul.ui.contactlist;

import java.util.ArrayList;
import java.util.Iterator;

import org.epidroid.epidroid.R;
import org.epidroid.epidroid.androsoul.engine.service.IAndroSoulService;
import org.epidroid.epidroid.androsoul.ui.AndroSoulActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

public class AddContactHandler {

	IAndroSoulService _service = null;
	AndroSoulActivity _context = null;

	public AddContactHandler(IAndroSoulService service,
			AndroSoulActivity context) {
		_service = service;
		_context = context;
	}

	/**
	 * Show dialog that asks the user for a contact's name and the list of
	 * groups where it belongs.
	 */
	public void showDialog() {
		AlertDialog.Builder alert = new AlertDialog.Builder(_context);
		alert.setTitle(R.string.addacontact);
		LayoutInflater factory = LayoutInflater.from(_context);
		final View alertDialogView = factory.inflate(
				R.layout.androsoul_add_contact, null);
		alert.setView(alertDialogView);

		ListView list = (ListView) alertDialogView
				.findViewById(R.id.addContactGroupList);
		final CheckListAdapter adapter = new CheckListAdapter(_context,
				R.layout.androsoul_list_item_checkbox,
				_service.getGroupsList(), null);
		list.setAdapter(adapter);

		alert.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int whichButton) {
				onOkClick(dialog, whichButton, alertDialogView, adapter);
			}
		});
		alert.setNegativeButton(R.string.cancel, null);
		alert.show();
	}

	private void onOkClick(DialogInterface dialog, int whichButton,
			View dialogView, CheckListAdapter adapter) {
		TextView textview = (TextView) dialogView
				.findViewById(R.id.contact_name);
		String name = textview.getText().toString();
		ArrayList<String> groups = adapter.getSelectedItems();

		if (name.equals("")) {
			// TODO: do not close the window when this happens
			_context.showToast(_context.getString(R.string.login_empty));
			return;
		}
		if (groups.isEmpty()) {
			// TODO: do not close the window when this happens
			_context.showToast(_context.getString(R.string.group_select));
			return;
		}

		Iterator<String> it = groups.iterator();
		while (it.hasNext())
			_service.addContact(name, _service.getGroupFromName(it.next()));
		_context.saveContacts();
		_context.showToast(_context.getString(R.string.contact) + " " + name + " " + _context.getString(R.string.added));
		_context.updateContactsListAdapter();
		_context.updateContactsPictures();
	}

}
